package com.lanyam.travel.base.controller;


import com.lanyam.travel.base.utils.Constant;
import com.lanyam.travel.base.utils.DataStatisticsUtil;
import com.lanyam.travel.base.utils.JSONResult;
import com.lanyam.travel.base.entity.GoodsDate;
import com.lanyam.travel.base.entity.GoodsInfo;
import com.lanyam.travel.base.entity.ScenicHotel;
import com.lanyam.travel.base.entity.vo.GoodsInfoVo;
import com.lanyam.travel.base.service.IGoodsDateService;
import com.lanyam.travel.base.service.IGoodsInfoService;
import com.lanyam.travel.base.service.IScenicHotelService;
import com.lanyam.travel.base.utils.JsonMapper;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;


@RestController
@RequestMapping("/goodsInfo")
public class GoodsInfoController {

    @Autowired
    private IGoodsInfoService goodsInfoService;
    
    @Autowired
    private IScenicHotelService scenicHotelService;
    
    @Autowired
    private IGoodsDateService goodsDateService;

    /**
               *  分页查询数据
     */
    @GetMapping("/getPage")
    public IPage<GoodsInfoVo> getPage (String queryMap,
                                                @RequestParam(name="page", defaultValue = "1") Integer page,
                                                @RequestParam(name="rows", defaultValue = "10") Integer rows) {
        Map<String, Object> query = JsonMapper.string2Obj(queryMap,new TypeReference<Map<String, Object>>() {});
        IPage<GoodsInfoVo> pageInfo = goodsInfoService.getPageGoodsInfo(query, page, rows);
        return pageInfo;
    }
    /**
     * 批量新增房间类型
     * @param id 酒店id
     * @param goodsList GoodsInfo中的参数goodsDateList中必填参数：price:价格；theDate：日期，格式2020/3/24，没有时分秒，remaindNum：票数量
     * @return
     */
    @RequestMapping("/batchAdd")
    public JSONResult batchAdd(String id,@RequestBody List<GoodsInfo> goodsList)
    {
    	if(StringUtils.isEmpty(id) || null == goodsList)
    	{
    		return JSONResult.errorMsg("参数不全");
    	}
    	ScenicHotel hotel = scenicHotelService.getScenicById(id);
    	if(null == hotel)
    	{
    		return JSONResult.errorMsg("获取酒店信息失败");
    	}
    	List<GoodsDate> insertList = new ArrayList<GoodsDate>();
    	for (GoodsInfo goodsInfo : goodsList) {
    		String goodsId = UUID.randomUUID().toString().replace("-", "");
    		goodsInfo.setId(goodsId);
    		goodsInfo.setShtId(id);
    		goodsInfoService.addGoodsInfo(goodsInfo);
    		//把商品日期表更新到一年半
    		List<GoodsDate> existList = goodsInfo.getGoodsDateList();
    		Calendar calendar = Calendar.getInstance();//获取当前日期0点的时候（00：00：00-24：00：00）
    		calendar.set(Calendar.HOUR_OF_DAY, 0);
    		calendar.set(Calendar.MINUTE, 0);
    		calendar.set(Calendar.SECOND, 0);
    		calendar.set(Calendar.MILLISECOND, 0);
    		int days = Constant.TICKET_DAYS;
    		GoodsDate goodsDate;
    		outer:for (int i = 0; i < days; i++) {
    			goodsDate = new GoodsDate();
    			if(null != existList && existList.size() > 0)
    			{
    				for (GoodsDate date : existList)
    				{
    					if(DataStatisticsUtil.sameDate(calendar.getTime(), date.getTheDate()))
    					{
    						goodsDate.setGoodsId(goodsId);
    						goodsDate.setPrice(date.getPrice());
    						goodsDate.setPriceDisparity(0);
    						goodsDate.setProductType(1);
    						goodsDate.setRemaindNum(date.getRemaindNum());
    						goodsDate.setTheDate(date.getTheDate());
    						insertList.add(goodsDate);
    						continue outer;
    					}
    				}
    			}
    			//走到这里说明这个日期没有设置过，添加为默认参数
    			goodsDate.setPrice(hotel.getPrice());
    			goodsDate.setRemaindNum(hotel.getTotalNum());
    			goodsDate.setGoodsId(goodsId);
    			goodsDate.setPriceDisparity(0);
    			goodsDate.setProductType(1);
    			goodsDate.setTheDate(calendar.getTime());//设置固定的时间为8：00：00
    			insertList.add(goodsDate);
    			calendar.add(Calendar.DAY_OF_YEAR, 1);
    		}
    		if(insertList.size() > 0)
    		{
    			goodsDateService.batchAddGoodsDates(insertList);
    		}
		}
    	return JSONResult.ok(goodsList);
    }
    

    /**
     * 新增数据,酒店单独调用此接口，景点和线路在创建的时候自动创建
     */
    @PostMapping("/add")
    public JSONResult add (@RequestBody GoodsInfo goodsInfo) {
        JSONResult result = null;
        try{
        	String id =UUID.randomUUID().toString().replace("-", "");
        	goodsInfo.setId(id);
            goodsInfoService.addGoodsInfo(goodsInfo);
            result = JSONResult.ok();
        }  catch (Exception e) {
            e.printStackTrace();
            String msg = e.getMessage();
            result = JSONResult.errorMsg(msg);
        }
        return result;
    }

    /**
     * 编辑数据
     */
    @PostMapping("/update")
    public JSONResult update (@RequestBody GoodsInfo goodsInfo) {
        JSONResult result = null;
        try{
            goodsInfoService.updateGoodsInfo(goodsInfo);
            result = JSONResult.ok();
        }  catch (Exception e) {
            e.printStackTrace();
            String msg = e.getMessage();
            result = JSONResult.errorMsg(msg);
        }
        return result;
    }

    /**
     * 删除数据
     */
    @PostMapping("/delById")
    public JSONResult delById (String id) {
        JSONResult result = null;
        try {
            goodsInfoService.delById(id);
            result = JSONResult.ok();
        }  catch (Exception e) {
            e.printStackTrace();
            String msg = e.getMessage();
            result = JSONResult.errorMsg(msg);
        }
        return result;
    }
    
    /**
	 * 获取产品里面的详细信息(主要指酒店)
	 * @param productId
	 * @return
	 */
	@PostMapping("/getGoodsListByProductId")
	public JSONResult getGoodsListByProductId(String productId)
	{
		List<GoodsInfo> goodsList = goodsInfoService.getGoodsInfoByProductId(productId);
		return JSONResult.ok(goodsList);
	}
}